<template>
  <el-select
    ref="formItem"
    v-bind="{ ...defaultAttrs, ...$attrs, ...item.attrs }"
    :value="selectValue"
    v-on="$listeners"
    @change="handleChange"
    @blur="blur"
    @focus="focus"
    @clear="clear"
  >
    <el-option
      v-for="opt in options"
      :key="getkey(opt)"
      :label="getlabel(opt)"
      :value="getvalue(opt)"
      :disabled="opt.disabled"
    />
  </el-select>
</template>

<script>
import formItemMixin from './form-item-mixin'
export default {
  name: 'FSelect',
  mixins: [formItemMixin],
  data() {
    return {
      defaultAttrs: {
        clearable: true,
        placeholder: '请选择'
      },
      myOptions: []
    }
  },
  computed: {
    options() {
      return this.item.options || this.myOptions
    },
    selectValue() {
      let detaultVal = ''
      if (this.item.attrs?.multiple) {
        detaultVal = []
      }
      return this.options && this.options.length ? this.value : detaultVal
    }
  },
  created() {
    this.loadOptions()
  },
  methods: {
    getlabel(opt) {
      try {
        return opt[this.item.optProps.label]
      } catch (e) {
        return opt.label
      }
    },
    getvalue(opt) {
      try {
        return opt[this.item.optProps.value]
      } catch (e) {
        return opt.value
      }
    },
    getkey(opt) {
      if (opt && opt['phone']) {
        return opt['phone']
      }
      return this.getvalue(opt)
    },
    loadOptions() {
      if (this.item.loadOptionsFn) {
        this.item.loadOptionsFn().then(res => {
          this.myOptions = res || []
        })
      }
    }
  }
}
</script>
